import {promptBox, base, toast} from 'nc-lightapp-front';
import {formatDate, getAppPageConfig, saveValidate} from "src/hrpub/common/utils/utils";

const {pagecode} = getAppPageConfig()

const {NCDatePicker, NCTooltip, NCFormControl} = base;
export default class HeaderAction {
    constructor(comp) {
        this.comp = comp;
    }

    /**
     * @desc: 返回及取消按钮事件回调
     * @param {type}
     * @return:
     */
    clickBackBtn = () => {
        const {dispatch, myLeave, editTable, meta: metas, form} = this.comp.props;
        let activeTab = myLeave.activeTab
        let tableCode = myLeave.activeTab + '_list';
        if (myLeave.activeTab === 'leaveoff' || myLeave.activeTab === 'tripoff') {
            myLeave.activeTab === 'leaveoff' ? tableCode = 'leave_list' : tableCode = 'trip_list'
            myLeave.activeTab === 'leaveoff' ? activeTab = 'leave' : activeTab = 'trip'
        }
        if (myLeave.isEdit) {
            promptBox(
                {
                    color: "warning",
                    title: myLeave.json['6040-00005'], /* 国际化处理： 提示*/
                    content: myLeave.json['6040-00006'], /* 国际化处理： 你确定要返回吗？*/
                    beSureBtnClick: () => {
                        dispatch({
                            type: 'myLeave/update',
                            payload: {
                                activeTab,
                                showMode: 'list',
                                isEdit: false,
                                headerTitle: myLeave.json['6040-00007'], //假勤申请
                                customTemplateItemKeys: [],
                            }
                        })
                    }
                })
        } else {
            dispatch({
                type: 'myLeave/update',
                payload: {
                    showMode: 'list',
                    activeTab,
                    headerTitle: myLeave.json['6040-00007'], //假勤申请
                    customTemplateItemKeys: [],
                }
            })
            dispatch({
                type: 'myLeave/queryListAction',
                payload: {
                    key: activeTab,
                    beginDate: myLeave.beginValue,
                    endDate: myLeave.endValue
                }
            }).then(res => {
                if (res.success) {
                    if (res.data) {
                        editTable.setTableData(tableCode, res.data[tableCode])
                        dispatch({
                            type: 'myLeave/update',
                            payload: {
                                [activeTab + 'PageInfo']: res.data[tableCode].pageInfo
                            }
                        })
                    } else {
                        editTable.setTableData(tableCode, {rows: []})
                        dispatch({
                            type: 'myLeave/update',
                            payload: {
                                [activeTab + 'PageInfo']: Object.assign({}, myLeave[activeTab + 'PageInfo'], {total: null})
                            }
                        })
                    }
                }
            })
        }
    }
    /**
     * @desc: 按钮时间注册回调函数
     * @param {type}
     * @return:
     */
    headerButtonClick = async (props, btncode) => {
        const {dispatch, myLeave, form} = this.comp.props
        const {setFormStatus, setAllFormValue, EmptyAllFormValue} = form

        let formCode = myLeave.activeTab + '_card'
        let tableCode = myLeave.activeTab + '_list'
        switch (btncode) {
            // 新增按钮  初始化 pk 默认数据
            case 'head_add':
                this.addBtnAction(formCode)
                break;
            case 'head_cancel':
                this.clickBackBtn();
                break;
            case 'head_query':
                dispatch({
                    type: 'myLeave/update',
                    payload: {
                        [myLeave.activeTab + 'PageInfo']: Object.assign({}, myLeave[myLeave.activeTab + 'PageInfo'], {
                            pageIndex: 1
                        })
                    }
                })
                this.searchAction(myLeave.activeTab, tableCode);
                break;
            case 'head_save':
                this.saveBill(myLeave.activeTab, formCode);
                break;
            case 'head_submit':
                this.submitBill(myLeave.activeTab, formCode);
                break;
            case 'head_refresh':
                this.searchAction(myLeave.activeTab, tableCode);
                break;
            case 'head_file':
                this.showUploader();
                break;
            case 'head_edit':
                this.editAction(formCode);
                break;
            case 'head_delete':
                this.deleteAction(myLeave.activeTab, formCode);
                break;
        }
    }
    /**
     * @desc: 新增按钮后事件
     * @param {type}
     * @return:
     */
    addBtnAction = (formCode) => {
        if (formCode === 'attendance_card') {
            this.addBatchAttend()
            return;
        }
        const {dispatch, myLeave, form, renderItem} = this.comp.props
        const {
            setFormStatus,
            setAllFormValue,
            EmptyAllFormValue,
            getFormItemsValue,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsRequired
        } = form
        EmptyAllFormValue(formCode)
        let cardDefaultVisiable = {}
        let cardDefaultDisabled = {}
        setItemsVisible(formCode, cardDefaultVisiable);
        setFormItemsDisabled(formCode, cardDefaultDisabled);
        setFormItemsRequired(formCode, cardDefaultVisiable);
        cardDefaultVisiable = null
        cardDefaultDisabled = null
        dispatch({
            type: 'myLeave/update',
            payload: {
                showMode: 'card',
                isEdit: true,
                headerTitle: myLeave.subTitle
            }
        })
        dispatch({
            type: 'myLeave/AddAction',
            payload: {
                key: myLeave.activeTab,
                operat: 0
            }
        }).then(res => {
            setAllFormValue({[formCode]: res.data[formCode]});
            let billId = getFormItemsValue(formCode, 'pk_' + myLeave.activeTab).value;
            let approvestatus = getFormItemsValue(formCode, 'approvestatus').value;
            dispatch({
                type: 'myLeave/update',
                payload: {
                    billId,
                    approvestatus
                }
            })
        })
        setFormStatus(formCode, 'add')
    }

    addBatchAttend = () => {
        const {dispatch} = this.comp.props

        dispatch({
            type: 'myLeave/update',
            payload: {
                batchModalVisible: true,
                isFreeAdd: false
            }
        })
    }

    /**
     * @desc: 表头点击修改事件触发
     * @param {type}
     * @return:
     */
    editAction = (formCode) => {
        const {dispatch, form, editTable, myLeave} = this.comp.props;
        form.setFormStatus(formCode, 'edit');
        let cardDefaultDisabled = {}
        form.setFormItemsDisabled(formCode, cardDefaultDisabled);
        cardDefaultDisabled = null;
        dispatch({
            type: 'myLeave/update',
            payload: {
                isEdit: true
            }
        })
    }

    /**
     * @desc: 单据删除事件触发
     * @param {type}
     * @return:
     */
    deleteAction = (activeTab, formCode) => {
        const {dispatch, myLeave} = this.comp.props
        const pk = myLeave.billId
        promptBox({
            color: "warning",
            title: myLeave.json['6040-00005'], /* 国际化处理： 提示*/
            content: myLeave.json['6040-000060'],
            beSureBtnClick: () => {
                dispatch({
                    type: 'myLeave/deleteAction',
                    payload: {
                        activeTab,
                        pk
                    }
                }).then(res => {
                    if (res.success) {
                        toast({
                            color: 'success',
                            content: myLeave.json['6040-000012']
                        })
                        this.clickBackBtn();
                    }
                })
            }
        })
    }

    searchAction = async (key, tableCode) => {
        const {dispatch, myLeave} = this.comp.props;
        let res = await dispatch({
            type: 'myLeave/queryListAction',
            payload: {
                key,
                beginDate: myLeave.beginValue,
                endDate: myLeave.endValue
            }
        })
        if (res.success) {
            if (res.data) {
                this.handleListData(res.data[tableCode], tableCode)
            } else {
                this.handleListData({rows: [], pageInfo: {... myLeave[myLeave.activeTab + 'PageInfo'], pageIndex: "1", total: null}}, tableCode)
            }
        }
    }
    /**
     * @desc: 数据请求完后处理函数封装
     * @param {type}
     * @return:
     */
    handleListData = (data, tableCode) => {
        const {dispatch, myLeave, editTable} = this.comp.props
        editTable.setTableData(tableCode, data)
        dispatch({
            type: 'myLeave/update',
            payload: {
                [myLeave.activeTab + 'PageInfo']: data.pageInfo
            }
        })
    }
    /**
     * @desc: 表单校验
     * @param {type}
     * @return:
     */
    checkBill = (formCode) => {
        const {dispatch, myLeave, form} = this.comp.props;
        const {isCheckNow} = form;
        return isCheckNow(formCode, 'warning')
    }
    /**
     * @desc: 保存单据
     * @param {type}
     * @return:
     */
    saveBill = async (key, formCode, submitFn) => {
        const {dispatch, myLeave, form} = this.comp.props
        const {getFormItemsValue, setFormItemsValue, setItemsVisible} = form;
        // 必填字段校验
        if (!this.checkBill(formCode)) {
            return;
        }
        //  单据提交前的手动校验  单据时间   时长字段
        if (!this.checkBillBymanual(formCode)) {
            return
        }

        setFormItemsValue(formCode, {
            'breastfeedingleaveday': {
                value: '',
                display: ''
            },
            'breastfeedingleaveway': {
                value: '',
                display: ''
            }
        })
        let tempForm = form.getAllFormValue(formCode);
        let formData = {
            model: tempForm
        }
        let dr_flag = form.getFormItemsValue(formCode, 'dr_flag');
        if (dr_flag && dr_flag === '1') {
            let pk = getFormItemsValue(formCode, 'mainid').value
            let pk_group = getFormItemsValue(formCode, 'pk_group').value
            dispatch({
                type: 'myLeave/deleteDrAction',
                payload: {
                    pk,
                    pk_group,
                    key: myLeave.activeTab
                }
            }).then(res => {
                dispatch({
                    type: 'myLeave/saveBillAction',
                    payload: {
                        key,
                        formData,
                        formCode
                    }
                }).then(res => {
                    if (res.success) {
                        form.setFormStatus(formCode, 'browse');
                        if (res.data && res.data[formCode]) {
                            form.setAllFormValue({
                                [formCode]: res.data[formCode]
                            })
                        }
                        dispatch({
                            type: 'myLeave/update',
                            payload: {
                                isEdit: false
                            }
                        });
                        if (typeof (submitFn) === 'function') {
                            submitFn()
                        }
                    }
                })
            })
        } else {
            saveValidate(this.comp.props, pagecode, formCode, null, 'form', null).then(() => {
                let durationObject = myLeave.durationObject
                dispatch({
                    type: 'myLeave/saveBillAction',
                    payload: {
                        key,
                        formData,
                        formCode,
                        durationObject
                    }
                }).then(res => {
                    if (res.success) {
                        form.setFormStatus(formCode, 'browse');
                        if (formCode === 'leave_card') {
                            form.setItemsVisible(formCode, {
                                vacationquota: false
                            })
                        }
                        if (res.data && res.data[formCode]) {
                            form.setAllFormValue({
                                [formCode]: res.data[formCode]
                            })
                        }
                        dispatch({
                            type: 'myLeave/update',
                            payload: {
                                isEdit: false
                            }
                        });
                        if (typeof (submitFn) === 'function') {
                            submitFn()
                        }
                    }
                })
            })
        }
    }

    /**
     * @desc: 单据未保存 先保存 再掉提交接口  已保存过，直接调提交接口
     *        通过表单的status来判断是否保存过
     * @param {type}
     * @return:
     */
    submitBill = (key, formCode) => {
        const {form} = this.comp.props;
        const {getFormItemsValue} = form;
        let pkKey = 'pk_' + key;
        let pk = getFormItemsValue(formCode, pkKey).value;
        this.saveBill(key, formCode, () => {
            this.submitFn(key, pk)
        })
    }

    submitFn = (key, pk) => {
        const {dispatch, myLeave} = this.comp.props;
        dispatch({
            type: 'myLeave/submitBillAction',
            payload: {
                key,
                pk
            }
        }).then(res => {
            if (res.success) {
                if (res.data && res.data.content) {
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            assignedData: res.data.content,
                            assignedDisplay: true
                        }
                    })
                } else {
                    toast({
                        color: 'success',
                        content: myLeave.json['6040-00004']  // 提交成功！
                    });
                    this.clickBackBtn();
                }
            }
        })
    }
    /**
     * @desc: 手动校验单据
     * @param {String} formCode  表单
     * @return:
     */
    checkBillBymanual = (formCode) => {
        return true
    }

    /**
     * @desc: 显示附件管理
     * @param {type}
     * @return:
     */
    showUploader = (ev) => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                showUploader: true
            }
        })
    }
    onBeginValueChange = (date) => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                beginValue: date
            }
        })
    }

    onEndValueChange = (date) => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                endValue: date
            }
        })
    }

    // 单据指派
    assignedBill = (value) => {
        const {dispatch, myLeave, form} = this.comp.props;
        const {getFormItemsValue} = form;
        let key = myLeave.activeTab
        let pkKey = 'pk_' + key;
        let formCode = key + '_card'
        let pk = getFormItemsValue(formCode, pkKey).value;
        dispatch({
            type: 'myLeave/submitBillAction',
            payload: {
                key,
                pk,
                content: value
            }
        }).then(res => {
            if (res.success) {
                toast({
                    color: 'success',
                    content: myLeave.json['6040-00004']  // 提交成功！
                });
                dispatch({
                    type: 'myLeave/update',
                    payload: {
                        assignedDisplay: false,
                        assignedData: null
                    }
                })
                this.clickBackBtn();
            }
        })
    }
    cancelAssigned = () => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                assignedDisplay: false,
                assignedData: null
            }
        })
    }

    didUpdate = () => {
        const {button, myLeave} = this.comp.props
        let canEdit = myLeave.approvestatus === '-1'
        let canSubmit = myLeave.approvestatus === '-1'
        button.setButtonsVisible({
            head_query: myLeave.showMode === 'list',
            head_refresh: myLeave.showMode === 'list',
            head_file: myLeave.showMode === 'card',
            head_cancel: myLeave.showMode === 'card' && myLeave.isEdit && canEdit,
            list_delete: myLeave.showMode === 'card' && !myLeave.isEdit,
            list_withdraw: myLeave.showMode === 'list',
            list_submit: myLeave.showMode === 'list'
        })
    }
}